var pagecount;
var pagecount2;

PageClick = function(pageclickednumber) {
    $("#pager").pager({ pagenumber: pageclickednumber, pagecount: pagecount, buttonClickCallback: PageClick });
    $("#gridList").setGridParam({ postData: { pagePlug: pageclickednumber} }).trigger("reloadGrid");  // Postdata을 넘겨주고 url로 지정된 ajax 호출하고 Grid을 Relo
}
PageClick2 = function(pageclickednumber) {
    $("#pager2").pager({ pagenumber: pageclickednumber, pagecount: pagecount2, buttonClickCallback: PageClick2 });
    $("#gridList2").setGridParam({ postData: { pagePlug: pageclickednumber} }).trigger("reloadGrid");  // Postdata을 넘겨주고 url로 지정된 ajax 호출하고 Grid을 Relo
}


$(document).ready(function(){
	initGridCommand();
	initGridCommandLog();
	
	/* 팝업 창 띄우기 */
	$("#btn_add_list").click(function(){
		 var gridSelRow = $("#gridList").getGridParam('selrow');//마지막 클릭한 row
		 var param = {
				 work_no : gridSelRow
		 };
		 
		 if(gridSelRow != null){
			 openModal('command_add.jsp', param, 416, 408);
		 }else{
			 alert("checkbox에 한개 이상 선택 되어야 합니다");
		 }
	});
	
	/* 작업리스트에 check된 date 삭제 */
	$("#btn_del_list").click(function(){
		 var gridSelRow = $("#gridList").getGridParam('selrow');//마지막 클릭한 row
		 var param = {
				 work_no : gridSelRow
		 };
		 
		 if(gridSelRow != null){
			 callAjax("deleteCommand.jsp", param, "COMMAND_DEL");
		 }else{
			 alert("checkbox에 한개 이상 선택 되어야 합니다");
		 }
	});
	
	/* 작업 상세보기에서 저장*/
	$("#btn_save_info").click(function(){
		 var gridSelRow = $("#gridList").getGridParam('selrow');//마지막 클릭한 row
		 var param = {
				 work_no : gridSelRow
		 };
		 
		 if(gridSelRow != null){
			 callAjax("insertCommandInfo.jsp", param, "COMMAND_ADD_INFO");
		 }else{
			 alert("checkbox에 한개 이상 선택 되어야 합니다");
		 }
	});
	
	/* 작업 상세보기에서 삭제 */
	$("#btn_del_info").click(function(){
		 var gridSelRow = $("#gridList").getGridParam('selrow');//마지막 클릭한 row
		 var param = {
				 work_no : gridSelRow
		 };
		 
		 if(gridSelRow != null){
			 callAjax("deleteCommand.jsp", param, "COMMAND_DEL");
		 }else{
			 alert("checkbox에 한개 이상 선택 되어야 합니다");
		 }
	});
	
	
	/* info + 클릭시 */
	$("#btn_add_info_list").on("click", function(event) {
		var url = "../command/insertAuth.jsp";
		var serviceName = "AUTH_ADD";
		var param = {
				auth_list : $("#auth_list").val(),
				auth_type1 : $("#auth_type1 option:selected").val(),
				auth_type2 : $("#auth_type2 option:selected").val()
		};
		callAjax(url,param, serviceName);
	});
	/* info - 클릭시 */
	$("#btn_del_info_list").on("click", function(event) {
		var url = "../command/deleteAuth.jsp";
		var serviceName = "AUTH_DEL";
		var param = {
				auth_list : $("#auth_list").val(),
				auth_type1 : $("#auth_type1 option:selected").val(),
				auth_type2 : $("#auth_type2 option:selected").val()
		};
		callAjax(url,param, serviceName);
	});
	
});

/* List clicked View */
function getCommandInfo(id){
	var url = "getCommandInfo.jsp";
	var param = {
		work_no : id
	};
	callAjax(url,param, "COMMAND_VIEW");
}

/* Log List clicked Popup View */
function command_detail(id){
	var url = "command_detail.jsp";
	var param = {
		ip_addr : id
	};
	openModal(url, param, 416, 408);
}

/* callAjax successAjax */
function successAjax(data, serviceName){
	if(serviceName == "COMMAND_VIEW"){
		/* Info value setting */
		$('#system_name').val(data.rows[0].system_name);
		$('#rule_kind').val(data.rows[0].rule_kind);
		$('#target').val(data.rows[0].target);
		$('#ex').val(data.rows[0].ex);
		$('#auth_list').val(data.rows[0].auth_list);
		$('#status1').val(data.rows[0].status);
		$('#last_sync_time').val(data.rows[0].last_sync_time);
	}else if(serviceName == "COMMAND_DEL"){
		alert(data.result);
	}else if(serviceName == "COMMAND_ADD_INFO"){
		alert(data.result);
	}else if(serviceName == "AUTH_ADD"){
		alert(data.result);
	}else if(serviceName == "AUTH_DEL"){
		alert(data.result);
	}
}
 
/* JqGrid Command List */
function initGridCommand() {
	$("#gridList").jqGrid({
		url:'getJqgridCommandList.jsp',
		mtype: 'post',
		//postData: {  },
		datatype: "json",
		colNames:['시스템명','대상','권한주체','상태','동기화일시'],
		colModel:[
				{name:'system_name',index:'system_name', width:50,align:"right",key:true},
				{name:'target',index:'target', width:80,align:"left"},
				{name:'authority',index:'authority', width:180,align:"left"},
				{name:"status",index:'status', width:100,align:"right"},
				{name:'sync',index:'sync', width:50,align:"right"}
			],
		//loadonce:true,
		rowList: [0,5,10,15,20],
		rowNum:5,
		height:240,
		autowidth : true,
		sortname: "system_name",
		sortorder: 'DESC',
		viewrecords: true,
		multiselect: true,//앞에 체크박스처리
		multikey: "",//multikey: "ctrlKey/shiftKey",
		pager: '#pager_id',
		//editurl: "server.json",
      
		onSelectRow: function(id){  //row가 선택되었을 경우
			getCommandInfo(id);
		},
		loadComplete : function(data){
			pagecount = data.total;
			$("#pager").pager({ pagenumber: data.page, pagecount: pagecount, buttonClickCallback: PageClick });
        },
		loadError : function(xhr,st,err) {
			//jQuery("#rsperror").html("Type: "+st+"; Response: "+ xhr.status + " "+xhr.statusText);
		},
		emptyrecords: "데이터가 존재하지 않습니다.",
		caption:'테이블',
		jsonReader: {
			repeatitems:false
		}
	});
	$("#gridList").jqGrid('navGrid','#pager_id',{edit:false,add:false,del:false,search:true});
}

/* JqGrid CommandLog List */
function initGridCommandLog() {
	$("#gridList2").jqGrid({
		url:'getJqgridCommandLogList.jsp',
		mtype: 'post',
		//postData: {  },
		datatype: "json",
		colNames:['기간','구분','작업','결과','중요도','작업자','원격지'],
		colModel:[
				{name:'calender',index:'calender', width:50,align:"right",key:true},
				{name:'type',index:'type', width:80,align:"left"},
				{name:'work',index:'work', width:180,align:"left"},
				{name:"result",index:'result', width:100,align:"right"},
				{name:'important',index:'important', width:50,align:"right"},
				{name:'worker',index:'worker', width:50,align:"right"},
				{name:'ip_addr',index:'ip_addr', width:50,align:"right"}
			],
		rowList: [0,5,10,15,20],
		rowNum:5,
		height:130,
		autowidth : true,
		sortname: "calender",
		sortorder: 'DESC',
		viewrecords: true,
		multiselect: false,//앞에 체크박스처리
		multikey: "",//multikey: "ctrlKey/shiftKey",
		pager: '#pager_id',
      
		onSelectRow: function(id){  //row가 선택되었을 경우
			var rowData = jQuery(this).getRowData(id); 
            var ip_addr= rowData['ip_addr'];//replace name with you column
            command_detail(ip_addr);
		},
		loadComplete : function(data){
			pagecount2 = data.total;
			$("#pager2").pager({ pagenumber: data.page, pagecount: pagecount2, buttonClickCallback: PageClick2 });
        },
		loadError : function(xhr,st,err) {
			//jQuery("#rsperror").html("Type: "+st+"; Response: "+ xhr.status + " "+xhr.statusText);
		},
		emptyrecords: "데이터가 존재하지 않습니다.",
		caption:'테이블',
		jsonReader: {
			repeatitems:false
		}
	});
	$("#gridList2").jqGrid('navGrid','#pager_id',{edit:false,add:false,del:false,search:true});
}
